package com.isunland.managesystem.ui;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.TextView;
import butterknife.BindView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.LatestAnnounceMent;
import com.isunland.managesystem.entity.LatestAnnounceMent.AnnounceMentDetail;
import com.isunland.managesystem.entity.LattestAnnounceMentDetailOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MenuUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.HashMap;
import org.json.JSONException;

public class LatestAnnounceMentDetailFragment extends BaseFragment {

  @BindView(R.id.wv_detail_latestAnnouncement) WebView wvDetail;
  @BindView(R.id.tv_file_latestAnnouncement) TextView tvFile;
  @BindView(R.id.tv_name) TextView tvName;
  @BindView(R.id.tv_date) TextView tvDate;
  @BindView(R.id.tv_title) TextView tvTitle;
  //@BindView(R.id.ll_fileAnnounce) LinearLayout llFile;
  private AnnounceMentDetail mAnnounceMentDetail;
  /** 由于列表和详情接口返回的数据不一致,详情中没有isRead,所有在列表中获取这个数据.\ */
  private String mIsRead;
  private String mTitle;
  private String mPublishDate;
  //@BindView(R.id.btn_send) Button btnSend;
  //@BindView(R.id.slv_readReceipt) MultiLinesView slvReadReceipt;

  /**
   * 把数据上一个Fragment传递过来的数据存储到bundle中
   */
  public static Fragment newInstance(AnnounceMentDetail announceMentDetail) {
    Bundle bundle = new Bundle();
    bundle.putSerializable("announceMentDetail", announceMentDetail);
    LatestAnnounceMentDetailFragment lamdf = new LatestAnnounceMentDetailFragment();
    lamdf.setArguments(bundle);
    return lamdf;
  }

  @Override public void initData() {
    super.initData();
    mAnnounceMentDetail = mBaseParams.getItem() instanceof AnnounceMentDetail
        ? (AnnounceMentDetail) mBaseParams.getItem()
        : new LatestAnnounceMent().new AnnounceMentDetail();
    //这几个字段列表中有,详情中没有.
    mIsRead = mAnnounceMentDetail.getIsRead();
    mTitle = mAnnounceMentDetail.getTitle();
    mPublishDate = mAnnounceMentDetail.getPublishDate();
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_latestannounce_detail;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(R.string.announceDetail);
    bindData();
    volleypostInit();
    tvFile.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(ExtraDownLoadDialogFragment.newInstance("", mAnnounceMentDetail.getFilePath()),
            0);
      }
    });
  }

  private void bindData() {
    //绑定数据
    String fileName = mAnnounceMentDetail.getFileOriginalName();
    tvTitle.setText(mTitle);
    tvFile.setVisibility(MyStringUtil.isEmpty(fileName) ? View.GONE : View.VISIBLE);
    tvFile.setText(MyStringUtil.equalsIgnoreCase("(null)", fileName) ? ""
        : MyStringUtil.connect("附件下载：", fileName));
    tvDate.setText(mPublishDate);
    tvName.setText(getString(R.string.publisherHolder, mAnnounceMentDetail.getRegStaffName()));
    //wvDetail.loadDataWithBaseURL(null, mAnnounceMentDetail.getDocContentDesc(), "text/html",
    //    "utf-8", null);
    String content = MyUtils.parseWebImage(mAnnounceMentDetail.getDocContentDesc());//图片自适应
    wvDetail.loadDataWithBaseURL(ApiConst.getUrlMain(), content, "text/html", "utf-8", null);//图文混排
    volleyPostIsRead();
  }

  /**
   * 将未读标记为已读
   */
  private void volleyPostIsRead() {
    if (!MyStringUtil.equalsIgnoreCase("F", mIsRead)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ANNOUNCE_READ);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mAnnounceMentDetail.getId());
    params.put("type", "mobile");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
        mActivity.setResult(
            MyStringUtil.equalsIgnoreCase(SuccessMessage.SUCCESS, successMessage.getResult())
                ? Activity.RESULT_OK : Activity.RESULT_CANCELED);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  /**
   * 初始化数据
   */
  private void volleypostInit() {
    if (MyStringUtil.isEmpty(mAnnounceMentDetail.getId())) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_DETAIL_LATEST_ANNOUNCEMENT_V290);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mAnnounceMentDetail.getId());
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("ifGetReadReceipt", "T");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String json) throws JSONException {
        LattestAnnounceMentDetailOriginal original =
            new Gson().fromJson(json, LattestAnnounceMentDetailOriginal.class);
        if (original.getData() != null) {
          mAnnounceMentDetail = original.getData();
          bindData();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    MenuUtil.addReadReceiptMenu(mActivity, menu, mAnnounceMentDetail.getReadReceipt(),
        mAnnounceMentDetail.getId());
  }
}
